package com.wfh.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.tauth.TAuthView;
import com.tencent.tauth.TencentOpenAPI;
import com.tencent.tauth.TencentOpenHost;
import com.tencent.tauth.bean.OpenId;
import com.tencent.tauth.http.Callback;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.wfh.R;
import com.wfh.share.QQShare;
import com.wfh.share.SinaWeiBo;
import com.wfh.util.MyDialog;
import com.wfh.util.Util;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ShareActivity extends CommonActivity {

	private EditText content;
	private Button share;
	private String imageurl;
	private MyDialog dialog;
	private boolean mThread = true;
	private String WXAppId = "wxd930ea5d5a258f4f"; // wx3bc43aacb5766c66
													// wxd930ea5d5a258f4f
	// qq认证
	public static final String APP_ID = "222222";// 替换为开发者的appkey，例如"1646212860";

	private IWXAPI api;
	private StatusesAPI status; // 新浪
	private SinaWeiBo sinaapi;
	private QQShare qqapi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		sinaapi=new SinaWeiBo(this);
		qqapi=new QQShare(this);
		super.onCreate(savedInstanceState, R.layout.activity_share);

		final Bundle bd = getIntent().getExtras();
		content = (EditText) findViewById(R.id.editText1);
		share = (Button) findViewById(R.id.button1);
		dialog = MyDialog.create(this);

		content.setText(bd.getString("content"));
		imageurl = bd.getString("imageurl");

		switch (bd.getInt("type")) {
		case 0:
			share.setText("分享到新浪微博");
			break;
		case 1:
			share.setText("分享到QQ空间");
			break;
		case 2:
			share.setText("分享到微信");
			break;
		default:
			break;
		}

		share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.setText("正在分享……");
				dialog.show();
				if (!mThread)
					return;
				mThread = false;
				share(bd.getInt("type"));
			}
		});

	}

	public void share(int type) {

		File file1 = new File(imageurl);
		if (!file1.exists()) {
			Util.showToast(ShareActivity.this, "分享的图片不存在");
			return;
		}

		switch (type) {
		case 0:
			if (Util.getShare(ShareActivity.this, "sinatoken") == null || Util.getShare(ShareActivity.this, "sinatoken").equals("")) {
				sinaapi.authorize();
				mThread = true;
				dialog.hide();
				return;
			}

			Oauth2AccessToken oauth = new Oauth2AccessToken();
			oauth.setToken(Util.getShare(this, "sinatoken"));
			oauth.setExpiresTime(Long.parseLong(Util.getShare(this,
					"sinaexpires")));
			if (status == null)
				status = new StatusesAPI(oauth);
			status.upload(content.getText().toString(), imageurl, null, null,
					sinalistener);
			break;

		case 1:
			if (Util.getShare(ShareActivity.this, "qqtoken") == null || Util.getShare(ShareActivity.this, "qqtoken").equals("")) {
				qqapi.authorize();
				dialog.hide();
				mThread = true;
				return;
			}

			String qqtoken = Util.getShare(ShareActivity.this, "qqtoken");
			String qqopenid = Util.getShare(ShareActivity.this, "qqopenid");
			String appid = ShareActivity.APP_ID;

			Bundle bundle = null;
			bundle = new Bundle();
			bundle = new Bundle();

			byte[] buff = null;
			try {
				File file = new File(imageurl);
				FileInputStream is = new FileInputStream(file);
				ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outSteam.write(buffer, 0, len);
				}
				outSteam.close();
				is.close();
				buff = outSteam.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			}

			bundle.putByteArray("picture", buff);// 必须.上传照片的文件名以及图片的内容（在发送请求时，图片内容以二进制数据流的形式发送，见下面的请求示例），注意照片名称不能超过30个字符。
			bundle.putString("photodesc", content.getText().toString());// 照片描述，注意照片描述不能超过200个字符。
			bundle.putString("title", "来自潍坊惠安卓平台" + System.currentTimeMillis()
					+ ".png");// 照片的命名，必须以.jpg, .gif, .png, .jpeg, .bmp此类后缀结尾。
			// bundle.putString("albumid",
			// "564546-asdfs-feawfe5545-45454");//相册id，不填则传到默认相册
			bundle.putString("x", "0-360");// 照片拍摄时的地理位置的经度。请使用原始数据（纯经纬度，0-360）。
			bundle.putString("y", "0-360");// 照片拍摄时的地理位置的纬度。请使用原始数据（纯经纬度，0-360）。
											// TencentOpenAPI2.sendStore(
			TencentOpenAPI.uploadPic(qqtoken, appid, qqopenid, bundle,
					QQCallback);

			break;

		case 2:
			// 实例化微信
			api = WXAPIFactory.createWXAPI(ShareActivity.this, WXAppId, true);
			api.registerApp(WXAppId);

			if (!api.isWXAppInstalled()) {
				Util.showToast(ShareActivity.this, "请安装微信");
				mThread = true;
			}

			WXImageObject imageobj = new WXImageObject();
			imageobj.setImagePath(imageurl);
			/*
			 * WXTextObject textobj = new WXTextObject(); textobj.text =
			 * content.getText().toString();
			 */

			// 构造一个WXMediaMessage
			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = imageobj;
			msg.description = content.getText().toString();

			Bitmap bmp = BitmapFactory.decodeFile(imageurl);
			Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
			bmp.recycle();
			msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

			// 构造一个req
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("img");
			req.transaction = String.valueOf(System.currentTimeMillis());
			req.message = msg;

			// 调用接口发送信息
			api.sendReq(req);
			dialog.hide();
			mThread = true;
			api.unregisterApp();
			break;
		}

	}

	/**
	 * 新浪微博监听
	 */
	RequestListener sinalistener = new RequestListener() {

		@Override
		public void onIOException(IOException arg0) {
			arg0.printStackTrace();
			Message msg = new Message();
			msg.what = 0;
			handler.sendMessage(msg);
		}

		@Override
		public void onError(WeiboException arg0) {
			arg0.printStackTrace();
			Message msg = new Message();
			msg.what = 1;
			handler.sendMessage(msg);
		}

		@Override
		public void onComplete(String arg0) {
			Message msg = new Message();
			msg.what = 2;
			handler.sendMessage(msg);
		}
	};

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			mThread = true;
			dialog.hide();
			switch (msg.what) {
			case 0:
				Util.showToast(ShareActivity.this, "联网失败");
				break;
			case 1:
				Util.showToast(ShareActivity.this, "分享失败,请重试");
				break;
			case 2:
				Util.showToast(ShareActivity.this, "分享成功");
				break;
			default:
				break;
			}

		}
	};

	/**
	 * QQopen监听
	 */
	Callback QQCallback = new Callback() {

		@Override
		public void onCancel(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFail(int arg0, String arg1) {
			ShareActivity.this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Util.showToast(ShareActivity.this, "分享失败");
					dialog.hide();
				}
			});

		}

		@Override
		public void onSuccess(Object arg0) {
			ShareActivity.this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Util.showToast(ShareActivity.this, "分享成功");
					dialog.hide();
				}
			});
		}

	};

	// 微信
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	
	
	
	@Override
	protected void onDestroy() {
		if (dialog != null)
			dialog.cancel();
		if (api != null)
			api.unregisterApp();
/*		if (status != null)
			status.destroy(RESULT_OK, sinalistener);
*/		qqapi.unReceiver();
		super.onDestroy();
	}

}
